# coding=utf8
import subprocess

import falcon
from wechat_sdk import WechatBasic, WechatConf
from wechat_sdk.exceptions import ParseError

from models.resource.uploaded import model_res_uploaded
from logging import getLogger

logger = getLogger('base')

conf1 = WechatConf(  # 这个是我的
    token='570255dc9ce2d50c762d9b9e',
    appid='wx41aab0b377e996fa',
    appsecret='32cf162764532ddc0b8e3284964c93c3',
    encrypt_mode='normal',  # 可选项：normal/compatible/safe，分别对应于 明文/兼容/安全 模式
    encoding_aes_key='9qBu9Rq3pveXUHpuFu5VdiKU71gZwt06RBHke31LVtd'  # 如果传入此值则必须保证同时传入 token, appid
)

conf2 = WechatConf(  # 王老板的
    token='570255dc9ce2d50c762d9b9e',
    appid='wx7e57737637924cc9',
    appsecret='0a195ec5bdd5f0130c2f398cdcbcc33f',
    encrypt_mode='normal',  # 可选项：normal/compatible/safe，分别对应于 明文/兼容/安全 模式
    encoding_aes_key='9qBu9Rq3pveXUHpuFu5VdiKU71gZwt06RBHke31LVtd'  # 如果传入此值则必须保证同时传入 token, appid
)

conf3 = WechatConf(  # 蔬菜的
    token='570255dc9ce2d50c762d9b9e',
    appid='wx719c12a978d76e38',
    appsecret='009daa4976d53e391a3664748a27286c',
    encrypt_mode='normal',  # 可选项：normal/compatible/safe，分别对应于 明文/兼容/安全 模式
    encoding_aes_key='9qBu9Rq3pveXUHpuFu5VdiKU71gZwt06RBHke31LVtd'  # 如果传入此值则必须保证同时传入 token, appid
)
# 简直完美2333
conf = conf1

wechat = WechatBasic(conf=conf)


class WxResource(object):
    def on_get(self, req, resp):
        data = req.params
        logger.info(data)
        # 用来验证
        if wechat.check_signature(data['signature'], data['timestamp'], data['nonce']):
            resp.body = data['echostr']
        else:
            resp.body = 'fail'
        resp.status = falcon.HTTP_200

    def on_post(self, req, resp):
        data = req.stream.read()
        try:
            wechat.parse_data(data)
        except ParseError:
            logger.debug("消息解析错误")
            resp.status = falcon.HTTP_500
            resp.body = "unknow error"
            return False
        print(wechat.message.source)
        # 改为获取素材后,使用素材
        news_list = []
        for news in model_res_uploaded.coll.find().limit(5):
            news_list.append({
                'title': news['Title'],
                'url': news['Url'],
                'picurl': news['Picurl']
            })

        resp.content_type = "application/xml"
        resp.status = falcon.HTTP_200  # This is the default status
        if len(news_list) == 0:
            resp.body = wechat.response_text(content="暂时没有新闻")
        else:
            resp.body = wechat.response_news(news_list)


app = falcon.API()

app.add_route('/', WxResource())

if __name__ == '__main__':
    subprocess.call('uwsgi --http :80 --wsgi-file wx_server.py --callable app', shell=True)
